const Router = require('koa-router')
const jwt = require('jsonwebtoken')
const { sequelize } = require('../database/db')
const { QueryTypes } = require('sequelize');
const fs = require('fs');
let private_key = fs.readFileSync('./pem/private_key.pem')

let router = new Router()

router.post('/connect', async(ctx) => {
    const { account, password } = ctx.request.body
    if (account && password) {
        const data = await sequelize.query(
            `SELECT id, account, name FROM Users WHERE account = '${account}' AND password = '${password}'`,
            { type: QueryTypes.SELECT }
        );
        if (data.length > 0) {
            const content = data[0]
            var token = jwt.sign(content, private_key, { expiresIn: 60 * 60 * 24});
            await sequelize.query(
                `update Users set token = '${token}' where id = ${content.id}`
            );
            content.token = token
            ctx.body = {
                code: 101,
                data: content,
                msg: '成功'
            }
        } else {
            ctx.body = {
                code: 101,
                data: null,
                msg: '账号或密码错误'
            }
        }
    } else {
        ctx.body = {
            code: 102,
            data: null,
            msg: ''
        }
    }
})

router.post('/reset', async(ctx) => {
    const { account, oldPsw, newPsw, id } = ctx.request.body
    if (account && oldPsw && newPsw && id) {
        let payload = await jwt.verify(ctx.request.headers.authorization, private_key);
        let { iat, exp } = payload;
        let data = new Date().getTime();
        if (data - iat * 1000 <= exp * 1000) {
            const data = await sequelize.query(
                `SELECT * FROM Users WHERE account = '${account}' AND password = '${oldPsw}'`
            );
            if (data.length > 0) {
                await sequelize.query(
                    `update Users set password = '${newPsw}' where id = ${id}`
                )
                ctx.body = {
                    code: 101,
                    data: { id },
                    msg: '成功'
                }
            } else {
                ctx.body = {
                    code: 102,
                    data: null,
                    msg: '原始密码错误'
                }
            }
        } else {
            ctx.body = {
                code: 201,
                data: null,
                msg: 'token过期'
            }
        }
    } else {
        ctx.body = {
            code: 102,
            data: null,
            msg: ''
        }
    }
})

module.exports = router
